package com.qf.java2102.qihaonan.hotel.dao.impl;

import com.qf.java2102.qihaonan.hotel.dao.IOrderDao;
import com.qf.java2102.qihaonan.hotel.pojo.Order;
import com.qf.java2102.qihaonan.hotel.utils.JdbcUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.SQLException;

/**
 * @author qhn
 * @version 1.0
 */
public class OrderDaoImpl implements IOrderDao {

    private QueryRunner queryRunner = null;

    @Override
    public int save(Order order) throws SQLException {

        queryRunner = new QueryRunner(JdbcUtils.getDataSource());
        String sql = "INSERT INTO `t_order` (`order_id`,`user_id`,`total_num`,`order_total_price`,`order_create_time`,`order_status`) " +
                "VALUES (?,?,?,?,?,?)";
        return queryRunner.update(JdbcUtils.getConnection(), sql,
                order.getOrderId(), order.getUserId(), order.getTotalNum(),
                order.getOrderTotalPrice(), order.getOrderCreateTime(), order.getOrderStatus());
    }

    @Override
    public Order findById(String orderId) throws SQLException {
        queryRunner = new QueryRunner(JdbcUtils.getDataSource());
        String sql = "SELECT\n" +
                "  `order_id` orderId,\n" +
                "  `table_id` tableId,\n" +
                "  `user_id` userId,\n" +
                "  `total_num` totalNum,\n" +
                "  `order_total_price` orderTotalPrice,\n" +
                "  `order_create_time` orderCreateTime,\n" +
                "  `order_status` orderStatus\n" +
                "FROM\n" +
                "  `t_order`\n" +
                "WHERE `order_id` = ?";
        return queryRunner.query(JdbcUtils.getConnection(), sql,new BeanHandler<>(Order.class), orderId);
    }

    @Override
    public int updateStatus(Order order) throws SQLException {
        queryRunner = new QueryRunner(JdbcUtils.getDataSource());
        String sql = "UPDATE `t_order` SET `order_status` = ? WHERE `order_id` = ?";
        return queryRunner.update(JdbcUtils.getConnection(), sql, order.getOrderStatus(), order.getOrderId());
    }
}
